package 多线程.集合案例;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author : K k
 * @date : 22:33 2020/10/16
 * Collections.synchronizedList保证集合线程安全
 */
public class SynchronizedListDemo<T> {
    public List<T> list;

    SynchronizedListDemo(){
        this.list= Collections.synchronizedList(new ArrayList<>());
    }

    public synchronized T getVal(int index){
        return list.get(index);
    }

    public void putVal(T t){
        list.add(t);
    }

    public static void main(String[] args) {
        SynchronizedListDemo<String > demo=new SynchronizedListDemo<String>();
        ArrayList<String> list=new ArrayList<>();
        for (int i=0;i<12000;i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    demo.putVal(Thread.currentThread().getName());
                    //list.add(Thread.currentThread().getName());
                }
            });
            thread.start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //System.out.println(list.size());
        System.out.println(demo.list.size());
    }
}
